﻿using Apps.BLL.Core;
using Apps.Common;
using Apps.DAL.S;
using Apps.Locale;
using Apps.Models;
using Apps.Models.S;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace Apps.BLL.S
{
    public partial class S_SAMPLE_CHECKBLL
    {
        public DBContainer db = new DBContainer();
        [Dependency]
        public S_SAMPLE_CHECKDETAILRepository m_DetailRep { get; set; }

        public S_SAMPLE_CHECKModel GetById(string checkid)
        {
            var queryData = m_Rep.GetList();
            return (from r in queryData
             where r.CHECK_ID == checkid 
             select new S_SAMPLE_CHECKModel
             {
                 CHECK_ID = r.CHECK_ID,
                 CHECK_USER_NAME = r.CHECK_USER.TrueName,
                 CHECKDETIAL = (from p in r.S_SAMPLE_CHECKDETAIL
                                select new S_SAMPLEModel
                                {
                                    SAMPLE_ID = p.S_SAMPLE.SAMPLE_ID,
                                    BATCH_CODE = p.S_SAMPLE.BATCH_CODE,
                                    MAKE_CODE = p.S_SAMPLE.MAKE_CODE,
                                    SAMPLE_CODE = p.S_SAMPLE.SAMPLE_CODE,
                                    RFID = p.S_SAMPLE.RFID,
                                    SAMPLE_TYPE = p.S_SAMPLE.SAMPLE_TYPE,
                                    CREATE_TIME = p.S_SAMPLE.CREATE_TIME,
                                    WEIGHT_STATUS = p.S_SAMPLE.WEIGHT_STATUS,
                                    WEIGHT = p.S_SAMPLE.WEIGHT,
                                    WEIGHT_USER_ID = p.S_SAMPLE.WEIGHT_USER_ID,
                                    WEIGHT_TIME = p.S_SAMPLE.WEIGHT_TIME,
                                    PRINT_COUNT = p.S_SAMPLE.PRINT_COUNT
                                }).ToList(),
                 CHECK_MODE = r.CHECK_MODE,
                 CHECK_NUMBER = r.CHECK_NUMBER,
                 CHECK_USER_ID = r.CHECK_USER_ID,
                 CHECK_TIME = r.CHECK_TIME,
                 STATUS = r.STATUS,
                 CHECK_TYPE = r.CHECK_TYPE,
                 REMARKS = r.REMARKS,
                 GET_NUMBER = r.GET_NUMBER,
                 TEMPLATE_ID = r.TEMPLATE_ID,
                 APPROVAL_STATUS = r.APPROVAL_STATUS,
                 SAMPLE_TYPE = r.SAMPLE_TYPE
             }).SingleOrDefault();
            //return TransHelper.TransExp<S_SAMPLE_CHECK, S_SAMPLE_CHECKModel>(m_Rep.GetItem(p => p.CHECK_ID == checkid));
        }

        public List<V_S_SAMPLEEXPIRE_RL> GetSAMPLEEXPIRE_RLList(ref GridPager pager, Expression<Func<V_S_SAMPLEEXPIRE_RL, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_S_SAMPLEEXPIRE_RL.Where(whereLambda);
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
        }
        
        public List<V_S_SAMPLEEXPIRE_RC> GetSAMPLEEXPIRE_RCList(ref GridPager pager, Expression<Func<V_S_SAMPLEEXPIRE_RC, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = db.V_S_SAMPLEEXPIRE_RC.Where(whereLambda);
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
        }

        /// <summary>
        /// 抽查样模块:0:抽查样,1:弃样取样,2:矿方取样
        /// </summary>
        /// <param name="pager"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="type">默认为0</param>
        /// <returns></returns>
        public List<S_SAMPLE_CHECKModel> GetRCList(ref GridPager pager, string startdate, string enddate, int type = 0)
        {
            IQueryable<S_SAMPLE_CHECK> queryData = null;
            queryData = m_Rep.GetList().Where(p => p.CHECK_TYPE == 0 && p.SAMPLE_TYPE == type);
            if (!string.IsNullOrWhiteSpace(startdate))
            {
                DateTime dStartTime = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);
                queryData = queryData.Where(a => a.CHECK_TIME > dStartTime);
            }
            if (!string.IsNullOrWhiteSpace(enddate))
            {
                DateTime dEndTime = DateTime.ParseExact(enddate, "yyyy-MM-dd", null).AddDays(1);
                queryData = queryData.Where(a => a.CHECK_TIME < dEndTime);
            }

            pager.totalRows = queryData.Count();

            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
            //return TransHelper.TransExpList<S_SAMPLE_CHECK, S_SAMPLE_CHECKModel>(queryData.ToList());
        }

        public List<S_SAMPLE_CHECKModel> GetRLList(ref GridPager pager, string startdate, string enddate, int type = 0)
        {
            IQueryable<S_SAMPLE_CHECK> queryData = null;
            queryData = m_Rep.GetList().Where(p => p.CHECK_TYPE == 1);
            if (!string.IsNullOrWhiteSpace(startdate))
            {
                DateTime dStartTime = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);
                queryData = queryData.Where(a => a.CHECK_TIME > dStartTime);
            }
            if (!string.IsNullOrWhiteSpace(enddate))
            {
                DateTime dEndTime = DateTime.ParseExact(enddate, "yyyy-MM-dd", null).AddDays(1);
                queryData = queryData.Where(a => a.CHECK_TIME < dEndTime);
            }

            pager.totalRows = queryData.Count();

            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
            //return TransHelper.TransExpList<S_SAMPLE_CHECK, S_SAMPLE_CHECKModel>(queryData.ToList());
        }

        public List<S_SAMPLE_CHECKDETAILModel> GetDetailById(string checkid)
        {
            return TransHelper.TransExpList<S_SAMPLE_CHECKDETAIL, S_SAMPLE_CHECKDETAILModel>(m_DetailRep.GetList(p => p.CHECK_ID == checkid).ToList());
        }

        public List<S_SAMPLE_CHECKDETAIL> GetListByCheckID(ref GridPager pager, string checkid)
        {
            using (DBContainer db = new DBContainer())
            {
                var queryData = m_DetailRep.GetList(p => p.CHECK_ID == checkid);
                    //db.S_SAMPLE_CHECKDETAIL.AsQueryable().Where(p => p.CHECK_ID == checkid).OrderBy(p => p.S_SAMPLE.BATCH_CODE).Select(p => p.S_SAMPLE);
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                //return TransHelper.TransExpList<S_SAMPLE, S_SAMPLEModel>(queryData.ToList());
                return queryData.ToList();
            }
        }

        public bool DeleteDetail(ref ValidationErrors errors, string checkid)
        {
            return m_DetailRep.Delete(p => p.CHECK_ID == checkid) > 0;
        }
        public bool CreateDetail(ref ValidationErrors errors, List<S_SAMPLE_CHECKDETAILModel> models)
        {
            try
            {
                foreach (var model in models)
                {
                    S_SAMPLE_CHECKDETAIL entity = m_DetailRep.GetById(model.CHECK_DETAIL_ID);
                    if (entity != null)
                    {
                        errors.Add(Resource.PrimaryRepeat);
                        return false;
                    }
                }
                var entities = TransHelper.TransExpList<S_SAMPLE_CHECKDETAILModel, S_SAMPLE_CHECKDETAIL>(models);
                
                if (m_DetailRep.Create(entities.ToArray()))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Create(ref ValidationErrors errors, S_SAMPLE_CHECKModel model, List<S_SAMPLE_CHECKDETAIL> models)
        {
            try
            {
                S_SAMPLE_CHECK entity = m_Rep.GetById(model.CHECK_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new S_SAMPLE_CHECK();
                entity.CHECK_ID = model.CHECK_ID;
                entity.CHECK_MODE = model.CHECK_MODE;
                entity.CHECK_NUMBER = model.CHECK_NUMBER;
                entity.CHECK_USER_ID = model.CHECK_USER_ID;
                entity.CHECK_TIME = model.CHECK_TIME;
                entity.STATUS = model.STATUS;
                entity.CHECK_TYPE = model.CHECK_TYPE;
                entity.REMARKS = model.REMARKS;
                entity.GET_NUMBER = model.GET_NUMBER;
                entity.TEMPLATE_ID = model.TEMPLATE_ID;
                entity.APPROVAL_STATUS = model.APPROVAL_STATUS;
                entity.SAMPLE_TYPE = model.SAMPLE_TYPE;

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_Rep.Create(entity) && m_DetailRep.Create(models.ToArray()))
                    {
                        transactionScope.Complete();
                        return true;
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Edit(ref ValidationErrors errors, S_SAMPLE_CHECKModel model, List<S_SAMPLE_CHECKDETAIL> models)
        {
            try
            {
                S_SAMPLE_CHECK entity = m_Rep.GetById(model.CHECK_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.CHECK_ID = model.CHECK_ID;
                entity.CHECK_MODE = model.CHECK_MODE;
                entity.CHECK_NUMBER = model.CHECK_NUMBER;
                entity.CHECK_USER_ID = model.CHECK_USER_ID;
                entity.CHECK_TIME = model.CHECK_TIME;
                entity.STATUS = model.STATUS;
                entity.CHECK_TYPE = model.CHECK_TYPE;
                entity.REMARKS = model.REMARKS;
                entity.GET_NUMBER = model.GET_NUMBER;
                entity.TEMPLATE_ID = model.TEMPLATE_ID;
                entity.APPROVAL_STATUS = model.APPROVAL_STATUS;
                entity.SAMPLE_TYPE = model.SAMPLE_TYPE;

                using (TransactionScope transactionScope = new TransactionScope())
                {
                    if (m_DetailRep.Delete(a => a.CHECK_ID == entity.CHECK_ID) >= 0 && m_Rep.Edit(entity))
                    {
                        if (models.Count > 0)
                        {
                            if (m_DetailRep.Create(models.ToArray()))
                            {
                                transactionScope.Complete();
                                return true;
                            }
                            else
                            {
                                Transaction.Current.Rollback();
                                return false;
                            }
                        }
                        transactionScope.Complete();
                        return true;
                    }
                    else
                    {
                        Transaction.Current.Rollback();
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }
    }
}
